package com.lk.feign.config;

import cn.hutool.core.util.StrUtil;
import com.lk.constant.SecurityConstant;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器 将token传递下游
 */
public class FeignInterceptorConfig {
    /**
     * 使用feign client访问别的微服务时，将上游传过来的client等信息放入header传递给下一个服务
     */
    @Bean
    public RequestInterceptor baseFeignInterceptor() {
        return template -> {
            //传递client
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String header = request.getHeader(SecurityConstant.TOKEN_HEAD);
            if (StrUtil.isNotEmpty(header)) {
                template.header(SecurityConstant.TOKEN_HEAD, header);
            }
        };
    }
}
